{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7d42e582",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "sys.path.append(os.path.abspath('../../code'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bcee14a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "from pathlib import Path\n",
    "\n",
    "import regex\n",
    "from collections import Counter\n",
    "\n",
    "import numpy as np\n",
    "np.set_printoptions(formatter={'float': lambda x: \"{0:0.3f}\".format(x)})\n",
    "import pandas as pd\n",
    "pd.set_option('display.max_columns', 15)\n",
    "pd.set_option('display.width', 320)\n",
    "\n",
    "from utils.io import read_label_config\n",
    "from utils.corpus import JsonlinesAnnotationsCorpus\n",
    "from utils.bsc_model import BSCModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "441cec08",
   "metadata": {},
   "outputs": [],
   "source": [
    "from types import SimpleNamespace\n",
    "\n",
    "args = SimpleNamespace()\n",
    "args.label_config_file = '../../data/annotation/doccano_label_config.json'\n",
    "args.input_file = '../../data/annotation/parsed/de-manifestos_annotations.jsonl'\n",
    "\n",
    "args.data_path = '../../data/annotation/annotations/'\n",
    "args.data_folder_pattern = 'de-manifestos'\n",
    "args.data_file_format = 'csv'\n",
    "\n",
    "args.output_file = '../../data/annotation/labeled/de-manifestos_all_labeled.jsonl'\n",
    "args.overwrite_output = False\n",
    "\n",
    "args.verbose = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "0485a7f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "job\n",
      "group-mentions-annotation-de-manifestos-round-01    1500\n",
      "group-mentions-annotation-de-manifestos-round-02    1427\n",
      "Name: count, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "fps = [str(fp) for fp in Path(args.data_path).glob(f'*{args.data_folder_pattern}*/*.{args.data_file_format}')]\n",
    "# read metadata\n",
    "metadata = pd.concat({fp.split('/')[-1].replace('_ids.csv', ''): pd.read_csv(fp) for fp in fps}, axis=0)\n",
    "metadata['job'] = metadata.index.get_level_values(0)\n",
    "metadata.reset_index(drop=True, inplace=True)\n",
    "print(metadata.job.value_counts())\n",
    "jobs = metadata.job.unique().tolist()\n",
    "jobs.sort()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9940ee7",
   "metadata": {},
   "source": [
    "## Read the annotations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c9b210fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 2923/2923 [00:05<00:00, 488.74it/s] \n"
     ]
    }
   ],
   "source": [
    "cat2code = read_label_config(args.label_config_file)\n",
    "acorp = JsonlinesAnnotationsCorpus(cat2code)\n",
    "acorp.load_from_jsonlines(args.input_file, verbose=args.verbose)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "56fd658e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# docs =  2923\n",
      "# gold items = 105\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'O': 0,\n",
       " 'I-social group': 1,\n",
       " 'B-social group': 7,\n",
       " 'I-political group': 2,\n",
       " 'B-political group': 8,\n",
       " 'I-political institution': 3,\n",
       " 'B-political institution': 9,\n",
       " 'I-organization, public institution, or collective actor': 4,\n",
       " 'B-organization, public institution, or collective actor': 10,\n",
       " 'I-implicit social group reference': 5,\n",
       " 'B-implicit social group reference': 11,\n",
       " 'I-unsure': 6,\n",
       " 'B-unsure': 12}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "n_docs = acorp.ndocs\n",
    "n_gold_labeled = len([1 for doc in acorp.docs if doc.n_labels > 0])\n",
    "print('# docs = ', n_docs)\n",
    "print('# gold items =', n_gold_labeled)\n",
    "acorp.label_map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "60a595f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ensure that 'unsure' never in GOLD annotations\n",
    "for doc in acorp.docs:\n",
    "    if doc.n_labels > 0 and cat2code['B-unsure'] in doc.labels['GOLD']:\n",
    "        print(doc.id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "cef9d9b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Counter({0: 1278,\n",
       "         1: 83,\n",
       "         4: 54,\n",
       "         5: 42,\n",
       "         10: 39,\n",
       "         7: 38,\n",
       "         3: 36,\n",
       "         9: 29,\n",
       "         11: 24,\n",
       "         2: 21,\n",
       "         8: 12})"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# count label types in GOlD\n",
    "# ensure that 'unsure' never in GOLD annotations\n",
    "gold_types = Counter()\n",
    "for doc in acorp.docs:\n",
    "    if 'GOLD' in doc.labels:\n",
    "        gold_types.update(doc.labels['GOLD'].tolist())\n",
    "gold_types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "278841e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# drop 'unsure' labels\n",
    "def recode_labels(codes):\n",
    "    out = codes.copy()\n",
    "    # set \"unsure\" to outside\n",
    "    out[codes ==  6] = 0\n",
    "    out[codes == 12] = 0\n",
    "    # reset all others\n",
    "    out[out>6] -= 1\n",
    "    return(out)\n",
    "\n",
    "for i in range(acorp.ndocs):\n",
    "    for j in range(acorp.docs[i].n_annotations):\n",
    "        acorp.docs[i].annotations[ acorp.docs[i].annotators[j] ] = recode_labels(acorp.docs[i].annotations[ acorp.docs[i].annotators[j] ])\n",
    "        for k in acorp.docs[i].labels.keys():\n",
    "            acorp.docs[i].labels[k] = recode_labels(acorp.docs[i].labels[k])\n",
    "\n",
    "idx = acorp.label_map.pop('B-unsure')\n",
    "acorp.label_map_inv.pop(idx)\n",
    "idx = acorp.label_map.pop('I-unsure')\n",
    "acorp.label_map_inv.pop(idx)\n",
    "\n",
    "# [print(c, 't', l) for c, l in acorp.label_map_inv.items()]\n",
    "for c in range(7,12): acorp.label_map[acorp.label_map_inv[c]] -= 1\n",
    "# [print(c, 't', l) for l, c in acorp.label_map.items()]\n",
    "\n",
    "acorp.label_map_inv = {c: l for l, c in acorp.label_map.items()}\n",
    "# [print(c, 't', l) for c, l in acorp.label_map_inv.items()]\n",
    "\n",
    "len(acorp.label_map) == len(acorp.label_map_inv)\n",
    "\n",
    "acorp.inside_labels = list(range(1, 6))\n",
    "acorp.beginning_labels = list(range(6, 11))\n",
    "\n",
    "acorp.ndocs = len(acorp.docs)\n",
    "acorp.doc_ids = [doc.id for doc in acorp.docs]\n",
    "acorp.doc_id2idx = {doc.id: i for i, doc in enumerate(acorp.docs)}\n",
    "acorp.doc_idx2id = {i: doc.id for i, doc in enumerate(acorp.docs)}\n",
    "\n",
    "acorp.annotator_label_counts = acorp._count_annotator_labels()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8b9c3ace",
   "metadata": {},
   "outputs": [],
   "source": [
    "annotations = acorp.annotator_label_counts\n",
    "gold = Counter()\n",
    "for labs in [doc.labels['GOLD'].tolist() for doc in acorp.docs if 'GOLD' in doc.labels]:\n",
    "    gold.update(labs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "80269515",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>emarie</th>\n",
       "      <th>sjasmin</th>\n",
       "      <th>gold</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>25194</td>\n",
       "      <td>25688</td>\n",
       "      <td>1316.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>523</td>\n",
       "      <td>516</td>\n",
       "      <td>83.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>449</td>\n",
       "      <td>442</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>118</td>\n",
       "      <td>71</td>\n",
       "      <td>21.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>125</td>\n",
       "      <td>101</td>\n",
       "      <td>29.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>210</td>\n",
       "      <td>182</td>\n",
       "      <td>36.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>245</td>\n",
       "      <td>228</td>\n",
       "      <td>39.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>334</td>\n",
       "      <td>214</td>\n",
       "      <td>54.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>304</td>\n",
       "      <td>264</td>\n",
       "      <td>24.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>236</td>\n",
       "      <td>125</td>\n",
       "      <td>42.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>163</td>\n",
       "      <td>128</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    emarie  sjasmin    gold\n",
       "0    25194    25688  1316.0\n",
       "1      523      516    83.0\n",
       "6      449      442    12.0\n",
       "2      118       71    21.0\n",
       "7      125      101    29.0\n",
       "3      210      182    36.0\n",
       "8      245      228    39.0\n",
       "4      334      214    54.0\n",
       "9      304      264    24.0\n",
       "5      236      125    42.0\n",
       "10     163      128     NaN"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame(annotations).join(pd.DataFrame({'gold': dict(gold)})).loc[acorp.label_map.values()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b31fb2de",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9913457377758547\n"
     ]
    }
   ],
   "source": [
    "# define custom token cleaning function\n",
    "def clean_tokens(x):\n",
    "\n",
    "    # insert special characters\n",
    "    if regex.match(r\"^\\p{Sc}\", x):\n",
    "        return(\"<MONEY>\")\n",
    "\n",
    "    if regex.match(r\"^\\d+([.,/-]\\d+)*\\w*$\", x):\n",
    "        return(\"<DIGITS>\")\n",
    "\n",
    "    return(x)\n",
    "\n",
    "# clean docs' tokens (in place) and collect results in Counter object\n",
    "cleaned_vocab = Counter()\n",
    "for i in range(acorp.ndocs):\n",
    "    cleaned_vocab.update(acorp.docs[i].clean_tokens(fun=clean_tokens))\n",
    "\n",
    "# reduces vocab size somewhat!\n",
    "print(len(cleaned_vocab)/len(acorp.vocab))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b9f9b37",
   "metadata": {},
   "source": [
    "## Annotation aggregation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a75660f0",
   "metadata": {},
   "source": [
    "### Prepare the Baysian sequene combination (BSC) sequence annotation model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "35f71c33",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parallel can run 10 jobs simultaneously, with 10 cores\n"
     ]
    }
   ],
   "source": [
    "amodel = BSCModel(acorp, max_iter=30, gold_labels='GOLD', verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "4616fe2f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# label classes: 11\n",
      "# annotators:    2\n",
      "# docs: 2923\n",
      "# tokens: 46449\n",
      "# docs with gold labels: 105\n",
      "# tokens with gold labels: 340\n"
     ]
    }
   ],
   "source": [
    "print('# label classes:', amodel.num_classes)\n",
    "print('# annotators:   ', amodel.num_annotators)\n",
    "print('# docs:', amodel.num_docs)\n",
    "print('# tokens:', amodel.num_tokens)\n",
    "print('# docs with gold labels:', (amodel.gold[amodel.doc_start == 1] > -1).sum())\n",
    "print('# tokens with gold labels:', (amodel.gold > 0).sum())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e1b3fab4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# inspect the alpha prior\n",
    "alpha0 = amodel.model.A.alpha0.copy()\n",
    "# note: default prior belief is that annotators assign correct label 2 out of 3 times\n",
    "alpha0[0,0]/alpha0[0,1:].sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "3a568c13",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                                                    =>O  =>I-soc  =>I-pol  =>I-pol  =>I-org  =>I-imp  =>B-soc  =>B-pol  =>B-pol  =>B-org  =>B-imp\n",
      "O                                                   6.0      0.0      0.0      0.0      0.0      0.0      1.0      1.0      1.0      1.0      1.0\n",
      "I-social group                                      1.0      1.0      0.0      0.0      0.0      0.0      0.0      1.0      1.0      1.0      1.0\n",
      "I-political group                                   1.0      0.0      1.0      0.0      0.0      0.0      1.0      0.0      1.0      1.0      1.0\n",
      "I-political institution                             1.0      0.0      0.0      1.0      0.0      0.0      1.0      1.0      0.0      1.0      1.0\n",
      "I-organization, public institution, or collecti...  1.0      0.0      0.0      0.0      1.0      0.0      1.0      1.0      1.0      0.0      1.0\n",
      "I-implicit social group reference                   1.0      0.0      0.0      0.0      0.0      1.0      1.0      1.0      1.0      1.0      0.0\n",
      "B-social group                                      1.0      5.0      0.0      0.0      0.0      0.0      0.0      1.0      1.0      1.0      1.0\n",
      "B-political group                                   1.0      0.0      5.0      0.0      0.0      0.0      1.0      0.0      1.0      1.0      1.0\n",
      "B-political institution                             1.0      0.0      0.0      5.0      0.0      0.0      1.0      1.0      0.0      1.0      1.0\n",
      "B-organization, public institution, or collecti...  1.0      0.0      0.0      0.0      5.0      0.0      1.0      1.0      1.0      0.0      1.0\n",
      "B-implicit social group reference                   1.0      0.0      0.0      0.0      0.0      5.0      1.0      1.0      1.0      1.0      0.0\n"
     ]
    }
   ],
   "source": [
    "# inspect transitions prior\n",
    "new_beta0 = amodel.model.LM.beta0.copy()\n",
    "cats = [k for k, v in sorted(acorp.label_map.items(), key=lambda item: item[1])]\n",
    "tmp = pd.DataFrame(new_beta0.round(2), index = cats, columns = ['=>'+c[:5]  for c in cats])\n",
    "# note: read this by rows and columns indicate label categories 0...12 and the cell (i, j) indicates the prior from\n",
    "#       probability that the label in column j follows the label in row i\n",
    "# for examples:\n",
    "# after the \"outside\" label, only itself and B-* labels are allowed\n",
    "tmp.iloc[[0]]\n",
    "# after the \"I-social group\" label, only itself, O, or the other B-* labels are allowed\n",
    "tmp.iloc[[1]]\n",
    "new_beta0[1, 6] = 1e-12\n",
    "# after the \"B-social group\" label, O, \"I-social group\", or any of the other B-* labels are allowed\n",
    "tmp.iloc[[6]]\n",
    "new_beta0[6, 6] = 1e-12\n",
    "\n",
    "# apply logic to each type\n",
    "for c in range(2, 6):\n",
    "    new_beta0[c, c+5] = 1e-12\n",
    "    new_beta0[c+5, c+5] = 1e-12\n",
    "\n",
    "# verify\n",
    "print(pd.DataFrame(new_beta0.round(2), index = cats, columns = ['=>'+c[:5]  for c in cats]))\n",
    "\n",
    "# reset\n",
    "amodel.reset_label_transitions_prior(new_beta0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3db97c9",
   "metadata": {},
   "source": [
    "### Fit the BSC model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ba4f1ebe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BSC: run() called with annotation matrix with shape = (46449, 2)\n",
      "BC iteration 0 in progress\n",
      "BC iteration 0: computed label probabilities\n",
      "BC iteration 0: updated label model\n",
      "BC iteration 0: updated worker models\n",
      "BC iteration 1 in progress\n",
      "BAC iteration 1: completed forward pass\n",
      "BAC iteration 1: completed backward pass\n",
      "BC iteration 1: computed label probabilities\n",
      "BC iteration 1: updated label model\n",
      "BC iteration 1: updated worker models\n",
      "Computing LB=-1246644.8807: label model and labels=-96209.6953, annotator model=-544.8750, features=-1149890.2635\n",
      "BSC: max. difference at iteration 2: inf\n",
      "BC iteration 2 in progress\n",
      "BAC iteration 2: completed forward pass\n",
      "BAC iteration 2: completed backward pass\n",
      "BC iteration 2: computed label probabilities\n",
      "BC iteration 2: updated label model\n",
      "BC iteration 2: updated worker models\n",
      "Computing LB=-1220044.3454: label model and labels=-71582.8906, annotator model=-317.5000, features=-1148143.9782\n",
      "BSC: max. difference at iteration 3: 26600.53532\n",
      "BC iteration 3 in progress\n",
      "BAC iteration 3: completed forward pass\n",
      "BAC iteration 3: completed backward pass\n",
      "BC iteration 3: computed label probabilities\n",
      "BC iteration 3: updated label model\n",
      "BC iteration 3: updated worker models\n",
      "Computing LB=-1217155.8657: label model and labels=-68810.8750, annotator model=-265.3750, features=-1148079.6704\n",
      "BSC: max. difference at iteration 4: 2888.47964\n",
      "BC iteration 4 in progress\n",
      "BAC iteration 4: completed forward pass\n",
      "BAC iteration 4: completed backward pass\n",
      "BC iteration 4: computed label probabilities\n",
      "BC iteration 4: updated label model\n",
      "BC iteration 4: updated worker models\n",
      "Computing LB=-1216711.1770: label model and labels=-68395.0391, annotator model=-258.2500, features=-1148057.8645\n",
      "BSC: max. difference at iteration 5: 444.68877\n",
      "BC iteration 5 in progress\n",
      "BAC iteration 5: completed forward pass\n",
      "BAC iteration 5: completed backward pass\n",
      "BC iteration 5: computed label probabilities\n",
      "BC iteration 5: updated label model\n",
      "BC iteration 5: updated worker models\n",
      "Computing LB=-1216572.1308: label model and labels=-68283.7500, annotator model=-256.0000, features=-1148032.4277\n",
      "BSC: max. difference at iteration 6: 139.04616\n",
      "BC iteration 6 in progress\n",
      "BAC iteration 6: completed forward pass\n",
      "BAC iteration 6: completed backward pass\n",
      "BC iteration 6: computed label probabilities\n",
      "BC iteration 6: updated label model\n",
      "BC iteration 6: updated worker models\n",
      "Computing LB=-1216479.1236: label model and labels=-68227.2969, annotator model=-254.6250, features=-1147997.1549\n",
      "BSC: max. difference at iteration 7: 93.00715\n",
      "BC iteration 7 in progress\n",
      "BAC iteration 7: completed forward pass\n",
      "BAC iteration 7: completed backward pass\n",
      "BC iteration 7: computed label probabilities\n",
      "BC iteration 7: updated label model\n",
      "BC iteration 7: updated worker models\n",
      "Computing LB=-1216355.0699: label model and labels=-68144.3594, annotator model=-254.0000, features=-1147956.7417\n",
      "BSC: max. difference at iteration 8: 124.05377\n",
      "BC iteration 8 in progress\n",
      "BAC iteration 8: completed forward pass\n",
      "BAC iteration 8: completed backward pass\n",
      "BC iteration 8: computed label probabilities\n",
      "BC iteration 8: updated label model\n",
      "BC iteration 8: updated worker models\n",
      "Computing LB=-1216223.2454: label model and labels=-68054.8203, annotator model=-253.0000, features=-1147915.4329\n",
      "BSC: max. difference at iteration 9: 131.82452\n",
      "BC iteration 9 in progress\n",
      "BAC iteration 9: completed forward pass\n",
      "BAC iteration 9: completed backward pass\n",
      "BC iteration 9: computed label probabilities\n",
      "BC iteration 9: updated label model\n",
      "BC iteration 9: updated worker models\n",
      "Computing LB=-1216106.3847: label model and labels=-67973.1016, annotator model=-251.0000, features=-1147882.2519\n",
      "BSC: max. difference at iteration 10: 116.86062\n",
      "BC iteration 10 in progress\n",
      "BAC iteration 10: completed forward pass\n",
      "BAC iteration 10: completed backward pass\n",
      "BC iteration 10: computed label probabilities\n",
      "BC iteration 10: updated label model\n",
      "BC iteration 10: updated worker models\n",
      "Computing LB=-1216019.8462: label model and labels=-67911.7188, annotator model=-248.2500, features=-1147859.9244\n",
      "BSC: max. difference at iteration 11: 86.53850\n",
      "BC iteration 11 in progress\n",
      "BAC iteration 11: completed forward pass\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/hlicht/miniforge3/envs/group_mention_detection/lib/python3.10/site-packages/joblib/externals/loky/process_executor.py:752: UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BAC iteration 11: completed backward pass\n",
      "BC iteration 11: computed label probabilities\n",
      "BC iteration 11: updated label model\n",
      "BC iteration 11: updated worker models\n",
      "Computing LB=-1215963.3792: label model and labels=-67871.2188, annotator model=-246.0000, features=-1147846.2073\n",
      "BSC: max. difference at iteration 12: 56.46706\n",
      "BC iteration 12 in progress\n",
      "BAC iteration 12: completed forward pass\n",
      "BAC iteration 12: completed backward pass\n",
      "BC iteration 12: computed label probabilities\n",
      "BC iteration 12: updated label model\n",
      "BC iteration 12: updated worker models\n",
      "Computing LB=-1215918.0748: label model and labels=-67839.4766, annotator model=-242.8750, features=-1147835.6920\n",
      "BSC: max. difference at iteration 13: 45.30440\n",
      "BC iteration 13 in progress\n",
      "BAC iteration 13: completed forward pass\n",
      "BAC iteration 13: completed backward pass\n",
      "BC iteration 13: computed label probabilities\n",
      "BC iteration 13: updated label model\n",
      "BC iteration 13: updated worker models\n",
      "Computing LB=-1215878.5683: label model and labels=-67810.7500, annotator model=-239.5000, features=-1147828.3183\n",
      "BSC: max. difference at iteration 14: 39.50643\n",
      "BC iteration 14 in progress\n",
      "BAC iteration 14: completed forward pass\n",
      "BAC iteration 14: completed backward pass\n",
      "BC iteration 14: computed label probabilities\n",
      "BC iteration 14: updated label model\n",
      "BC iteration 14: updated worker models\n",
      "Computing LB=-1215853.1036: label model and labels=-67791.6328, annotator model=-238.0000, features=-1147823.4630\n",
      "BSC: max. difference at iteration 15: 25.46472\n",
      "BC iteration 15 in progress\n",
      "BAC iteration 15: completed forward pass\n",
      "BAC iteration 15: completed backward pass\n",
      "BC iteration 15: computed label probabilities\n",
      "BC iteration 15: updated label model\n",
      "BC iteration 15: updated worker models\n",
      "Computing LB=-1215837.1090: label model and labels=-67781.1875, annotator model=-236.7500, features=-1147819.2027\n",
      "BSC: max. difference at iteration 16: 15.99462\n",
      "BC iteration 16 in progress\n",
      "BAC iteration 16: completed forward pass\n",
      "BAC iteration 16: completed backward pass\n",
      "BC iteration 16: computed label probabilities\n",
      "BC iteration 16: updated label model\n",
      "BC iteration 16: updated worker models\n",
      "Computing LB=-1215822.9951: label model and labels=-67774.6562, annotator model=-236.5000, features=-1147811.8076\n",
      "BSC: max. difference at iteration 17: 14.11387\n",
      "BC iteration 17 in progress\n",
      "BAC iteration 17: completed forward pass\n",
      "BAC iteration 17: completed backward pass\n",
      "BC iteration 17: computed label probabilities\n",
      "BC iteration 17: updated label model\n",
      "BC iteration 17: updated worker models\n",
      "Computing LB=-1215804.6855: label model and labels=-67760.5234, annotator model=-236.1250, features=-1147808.0761\n",
      "BSC: max. difference at iteration 18: 18.30967\n",
      "BC iteration 18 in progress\n",
      "BAC iteration 18: completed forward pass\n",
      "BAC iteration 18: completed backward pass\n",
      "BC iteration 18: computed label probabilities\n",
      "BC iteration 18: updated label model\n",
      "BC iteration 18: updated worker models\n",
      "Computing LB=-1215795.5556: label model and labels=-67753.6016, annotator model=-235.6250, features=-1147806.3603\n",
      "BSC: max. difference at iteration 19: 9.12986\n",
      "BC iteration 19 in progress\n",
      "BAC iteration 19: completed forward pass\n",
      "BAC iteration 19: completed backward pass\n",
      "BC iteration 19: computed label probabilities\n",
      "BC iteration 19: updated label model\n",
      "BC iteration 19: updated worker models\n",
      "Computing LB=-1215787.7172: label model and labels=-67747.6016, annotator model=-235.1250, features=-1147805.0141\n",
      "BSC: max. difference at iteration 20: 7.83840\n",
      "BC iteration 20 in progress\n",
      "BAC iteration 20: completed forward pass\n",
      "BAC iteration 20: completed backward pass\n",
      "BC iteration 20: computed label probabilities\n",
      "BC iteration 20: updated label model\n",
      "BC iteration 20: updated worker models\n",
      "Computing LB=-1215781.8455: label model and labels=-67742.7109, annotator model=-234.8750, features=-1147804.2049\n",
      "BSC: max. difference at iteration 21: 5.87168\n",
      "BC iteration 21 in progress\n",
      "BAC iteration 21: completed forward pass\n",
      "BAC iteration 21: completed backward pass\n",
      "BC iteration 21: computed label probabilities\n",
      "BC iteration 21: updated label model\n",
      "BC iteration 21: updated worker models\n",
      "Computing LB=-1215778.3695: label model and labels=-67739.7656, annotator model=-234.8750, features=-1147803.7523\n",
      "BSC: max. difference at iteration 22: 3.47603\n",
      "BC iteration 22 in progress\n",
      "BAC iteration 22: completed forward pass\n",
      "BAC iteration 22: completed backward pass\n",
      "BC iteration 22: computed label probabilities\n",
      "BC iteration 22: updated label model\n",
      "BC iteration 22: updated worker models\n",
      "Computing LB=-1215776.3529: label model and labels=-67738.1016, annotator model=-234.8750, features=-1147803.4388\n",
      "BSC: max. difference at iteration 23: 2.01662\n",
      "BC iteration 23 in progress\n",
      "BAC iteration 23: completed forward pass\n",
      "BAC iteration 23: completed backward pass\n",
      "BC iteration 23: computed label probabilities\n",
      "BC iteration 23: updated label model\n",
      "BC iteration 23: updated worker models\n",
      "Computing LB=-1215774.7247: label model and labels=-67736.8750, annotator model=-234.7500, features=-1147803.0841\n",
      "BSC: max. difference at iteration 24: 1.62812\n",
      "BC iteration 24 in progress\n",
      "BAC iteration 24: completed forward pass\n",
      "BAC iteration 24: completed backward pass\n",
      "BC iteration 24: computed label probabilities\n",
      "BC iteration 24: updated label model\n",
      "BC iteration 24: updated worker models\n",
      "Computing LB=-1215772.7222: label model and labels=-67735.6484, annotator model=-234.5000, features=-1147802.5425\n",
      "BSC: max. difference at iteration 25: 2.00253\n",
      "BC iteration 25 in progress\n",
      "BAC iteration 25: completed forward pass\n",
      "BAC iteration 25: completed backward pass\n",
      "BC iteration 25: computed label probabilities\n",
      "BC iteration 25: updated label model\n",
      "BC iteration 25: updated worker models\n",
      "Computing LB=-1215770.4329: label model and labels=-67734.0859, annotator model=-234.3750, features=-1147801.9173\n",
      "BSC: max. difference at iteration 26: 2.28933\n",
      "BC iteration 26 in progress\n",
      "BAC iteration 26: completed forward pass\n",
      "BAC iteration 26: completed backward pass\n",
      "BC iteration 26: computed label probabilities\n",
      "BC iteration 26: updated label model\n",
      "BC iteration 26: updated worker models\n",
      "Computing LB=-1215768.7417: label model and labels=-67732.5234, annotator model=-234.5000, features=-1147801.6636\n",
      "BSC: max. difference at iteration 27: 1.69114\n",
      "BC iteration 27 in progress\n",
      "BAC iteration 27: completed forward pass\n",
      "BAC iteration 27: completed backward pass\n",
      "BC iteration 27: computed label probabilities\n",
      "BC iteration 27: updated label model\n",
      "BC iteration 27: updated worker models\n",
      "Computing LB=-1215767.3867: label model and labels=-67731.4609, annotator model=-234.3750, features=-1147801.5664\n",
      "BSC: max. difference at iteration 28: 1.35503\n",
      "BC iteration 28 in progress\n",
      "BAC iteration 28: completed forward pass\n",
      "BAC iteration 28: completed backward pass\n",
      "BC iteration 28: computed label probabilities\n",
      "BC iteration 28: updated label model\n",
      "BC iteration 28: updated worker models\n",
      "Computing LB=-1215766.4967: label model and labels=-67730.6172, annotator model=-234.3750, features=-1147801.4889\n",
      "BSC: max. difference at iteration 29: 0.89004\n",
      "BC iteration 29 in progress\n",
      "BAC iteration 29: completed forward pass\n",
      "BAC iteration 29: completed backward pass\n",
      "BC iteration 29: computed label probabilities\n",
      "BC iteration 29: updated label model\n",
      "BC iteration 29: updated worker models\n",
      "BC iteration 30: computing most likely labels...\n",
      "BAC iteration 30: completed forward pass\n",
      "BAC iteration 30: completed backward pass\n",
      "BC iteration 30: fitting/predicting complete.\n"
     ]
    }
   ],
   "source": [
    "# fit model\n",
    "amodel.fit_predict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "821b1bc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "283.32099145802204\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[inf,\n",
       " 26600.535315625835,\n",
       " 2888.479642565595,\n",
       " 444.6887653134763,\n",
       " 139.04616380715743,\n",
       " 93.00714982766658,\n",
       " 124.05376527016051,\n",
       " 131.82451964681968,\n",
       " 116.86061852844432,\n",
       " 86.53850379167125,\n",
       " 56.4670614216011,\n",
       " 45.304399782791734,\n",
       " 39.50643207714893,\n",
       " 25.464724241755903,\n",
       " 15.99461836181581,\n",
       " 14.113870717585087,\n",
       " 18.30966693442315,\n",
       " 9.12986496440135,\n",
       " 7.838402014225721,\n",
       " 5.871683999197558,\n",
       " 3.4760293611325324,\n",
       " 2.016621259506792,\n",
       " 1.628119511064142,\n",
       " 2.002525717020035,\n",
       " 2.2893328964710236,\n",
       " 1.6911360225640237,\n",
       " 1.3550263370852917,\n",
       " 0.8900373282376677]"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(amodel.runtime_)\n",
    "amodel.model.convergence_history"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31caa9b5",
   "metadata": {},
   "source": [
    "### add sentence metadata to posterior label estimates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "4cf3a7b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "metadata.set_index('uid', inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ef99669e",
   "metadata": {},
   "outputs": [],
   "source": [
    "for doc in amodel.corpus.docs:\n",
    "    doc.metadata = {k: v for k, v in dict(metadata.loc[doc.id]).items() if not pd.isna(v)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "3234da91",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([ True]), array([2923]))"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.unique(np.array([hasattr(doc, 'metadata') for doc in amodel.corpus.docs]), return_counts=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1bba1d5",
   "metadata": {},
   "source": [
    "## Write to disk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "dbcd0e12",
   "metadata": {},
   "outputs": [],
   "source": [
    "def _jsonify(self, fields=['id', 'text', 'tokens', 'annotations', 'labels', 'metadata']):\n",
    "    out = {k: self.__dict__[k] for k in fields if hasattr(self, k)}\n",
    "    if 'annotations' in out.keys():\n",
    "        out['annotations'] = {k: v.tolist() for k, v in out['annotations'].items()}\n",
    "    if 'labels' in out.keys():\n",
    "        out['labels'] = {k: v.tolist() for k, v in out['labels'].items()}\n",
    "        if len(out['labels']) == 0:\n",
    "            out['labels'] = None\n",
    "    if 'metadata' in out.keys():\n",
    "        if len(out['metadata']) == 0:\n",
    "            out['metadata'] = None\n",
    "    return json.dumps(out)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f270ad74",
   "metadata": {},
   "outputs": [],
   "source": [
    "if not os.path.exists(args.output_file) or args.overwrite_output:\n",
    "    with open(args.output_file, mode='w', encoding='utf-8') as writer:\n",
    "        for doc in amodel.corpus.docs:\n",
    "            writer.write(_jsonify(doc)+'\\n')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "group_mention_detection",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
